package com.hjm.project.terminal.library.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.hjm.common.utils.security.ShiroUtils;
import com.hjm.common.utils.yh.GetTmk;
import com.hjm.project.job.task.service.IJobTaskService;
import com.hjm.project.terminal.library.domain.TerminalLibrary;
import com.hjm.project.terminal.library.domain.TerminalLibraryModelVo;
import com.hjm.project.terminal.library.domain.TerminalSecretKey;
import com.hjm.project.terminal.library.service.ITerminalLibraryService;
import com.hjm.project.terminal.manufacturer.service.IManufacturerService;
import com.hjm.project.terminal.model.domain.TerminalModel;
import com.hjm.project.terminal.model.service.ITerminalModelService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.hjm.framework.aspectj.lang.annotation.Log;
import com.hjm.framework.aspectj.lang.enums.BusinessType;
import com.hjm.framework.web.controller.BaseController;
import com.hjm.framework.web.domain.AjaxResult;
import com.hjm.common.utils.poi.ExcelUtil;
import com.hjm.framework.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * 终端库Controller
 * 
 * @author LOVE
 * @date 2020-11-26
 */
@Controller
@RequestMapping("/terminal/library")
public class TerminalLibraryController extends BaseController
{
    private static final Logger logger = LoggerFactory.getLogger("sys-user");

    private String prefix = "terminal/library";

    @Resource
    private ITerminalLibraryService terminalLibraryService;
    @Resource
    private ITerminalModelService terminalModelService;
    @Resource
    private IManufacturerService manufacturerService;
    @Resource
    private IJobTaskService jobTaskService;

    @RequiresPermissions("terminal:library:view")
    @GetMapping()
    public String library(ModelMap mmap) throws Exception {
        List<Map> manufacturer = manufacturerService.getManufacturer(ShiroUtils.isAgent() ? ShiroUtils.getLoginAgentNum() : null);
        mmap.put("manufacturer",manufacturer);
        return prefix + "/library";
    }

    /**
     * 查询终端库列表
     */
    @RequiresPermissions("terminal:library:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(TerminalLibrary terminalLibrary)
    {
        startPage();
        List<TerminalLibrary> list = terminalLibraryService.selectTerminalLibraryList(terminalLibrary);
        return getDataTable(list);
    }

    /**
     * 导出终端库列表
     */
    @RequiresPermissions("terminal:library:export")
    @Log(title = "终端库", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(TerminalLibrary terminalLibrary)
    {
        List<TerminalLibrary> list = terminalLibraryService.selectTerminalLibraryList(terminalLibrary);
        ExcelUtil<TerminalLibrary> util = new ExcelUtil<TerminalLibrary>(TerminalLibrary.class);
        jobTaskService.asyncDownLoad("library",Long.parseLong("1"),"导出SN",this.getSysUser().getLoginName(),list,util);
        //util.exportExcel(list, "library")
        return AjaxResult.success("操作成功，前往下载队列查看");
    }


    /**
     * 下载终端入库/划拨模版
     */
    @Log(title = "终端入库/划拨模版", businessType = BusinessType.EXPORT)
    @GetMapping("/exportModel")
    @ResponseBody
    public AjaxResult exportModel() {
        ExcelUtil<TerminalLibraryModelVo> util = new ExcelUtil<TerminalLibraryModelVo>(TerminalLibraryModelVo.class);
        return util.importTemplateExcel("终端模板");
    }



    /**
     * 新增终端库
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存终端库
     */
    @RequiresPermissions("terminal:library:add")
    @Log(title = "终端库", businessType = BusinessType.EXPORT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(String id,Integer count)
    {
        List<TerminalSecretKey> list = new ArrayList<TerminalSecretKey>();
        try{
            if (count>10000){
                return AjaxResult.warn("生成密钥的数量不得多于1万条!");
            }
            TerminalModel terminalModel=new TerminalModel();
            terminalModel=terminalModelService.selectTerminalModelById(Long.valueOf(id));
            Map para = new HashMap<String, Object>();
            para.put("manu", terminalModel.getManuName());
            para.put("result", terminalModel.getResult());
            para.put("term", terminalModel.getModel());
            para.put("count", count);
            para.put("createMan", ShiroUtils.getLoginName());
            GetTmk gt = new GetTmk();
            for (int i = 0; i < count; i++) {
                TerminalSecretKey t=new TerminalSecretKey();
                String posno=terminalLibraryService.getPosNo();
                para.put("posno",posno);
                String[] gta=gt.getTmk(para);
                t.setPosno(posno);
                t.setTmk(gta[0].substring(0, 32));
                t.setCiphertext(gta[1].substring(0, 32));
                t.setCkv(gta[0].substring(32, 48));
                logger.info("上送密钥响应数据:" + JSON.toJSONString(t));
                list.add(i,t);
            }
            ExcelUtil<TerminalSecretKey> util = new ExcelUtil<TerminalSecretKey>(TerminalSecretKey.class);
            jobTaskService.asyncDownLoad("生成密钥文件",Long.parseLong("2"),"生成密钥文件",this.getSysUser().getLoginName(),list,util);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("操作失败,系统异常");
        }
        //return util.exportExcel(list, "生成密钥文件");
        return AjaxResult.success("操作成功，前往下载队列查看");
    }

    /**
     * 修改终端库
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        TerminalLibrary terminalLibrary = terminalLibraryService.selectTerminalLibraryById(id);
        mmap.put("terminalLibrary", terminalLibrary);
        return prefix + "/edit";
    }

    /**
     * 修改保存终端库
     */
    @RequiresPermissions("terminal:library:edit")
    @Log(title = "终端库", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(TerminalLibrary terminalLibrary)
    {
        return toAjax(terminalLibraryService.updateTerminalLibrary(terminalLibrary));
    }

    /**
     * 删除终端库
     */
    @RequiresPermissions("terminal:library:remove")
    @Log(title = "终端库", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(terminalLibraryService.deleteTerminalLibraryByIds(ids));
    }
    /**
     * 生成终端
     */
    @GetMapping("/addPos")
    public String addPos(ModelMap map)
    {
        return prefix + "/addPos";
    }

    @Log(title = "终端入库", businessType = BusinessType.INSERT)
    @PostMapping("/savePos")
    @ResponseBody
    public AjaxResult savePos(String term_num,String source,String sim_fee,String service_fee,String posNetwork,String pos_version, MultipartFile file){
        Map<String, String> map=new HashMap<>();
        try{
            TerminalModel terminalModel = new TerminalModel();
            terminalModel=terminalModelService.selectTerminalModelById(Long.valueOf(term_num));
            Map para = Maps.newHashMap();
            para.put("manu", terminalModel.getManuNum());
            para.put("term", term_num);
            para.put("createMan", ShiroUtils.getLoginName());
            para.put("source", source);
            para.put("posNetwork", posNetwork);
            para.put("type", terminalModel.getType());
            para.put("model", terminalModel.getModel());
            para.put("sim_fee", sim_fee);
            para.put("service_fee", service_fee);
            para.put("pos_version", pos_version);
            //导入终端信息
            File files = File.createTempFile("prefix", "_" + file.getOriginalFilename());
            file.transferTo(files);
            map = terminalLibraryService.addTerminal_library(files,para);
        }catch (Exception e){
            e.printStackTrace();
        }
        if ("00".equals(map.get("code"))) {
            //增加一条导入记录
            jobTaskService.asyncUploadFile("4","终端文件入库",ShiroUtils.getSysUser().getLoginName(),file);
            return AjaxResult.success(map.get("msg"));
        } else {
            return AjaxResult.warn(map.get("msg"));
        }
    }

}
